package book.jdbc;

import java.sql.*;

public class ConnectToMysql {
    protected String msodbc = "com.mysql.cj.jdbc.Driver"; //驱动
    protected String url = "jdbc:mysql://localhost:3306/library?serverTimezone=UTC"; //url
    protected String user = "root"; //
    protected String password = "mysql";
    protected Connection con;
    protected Statement st; // 链接

    public ConnectToMysql() {

    }

    /**
     * 修改数据库
     *
     * @param databaseName 数据库名
     */
    public ConnectToMysql(String databaseName) {
        url = "jdbc:mysql://localhost:3306/" + databaseName + "?serverTimezone=UTC";
    }

    /**
     * 打开链接
     *
     * @throws ClassNotFoundException 驱动未找到
     * @throws SQLException           数据库错误
     */
    private void connect() throws ClassNotFoundException, SQLException {
        Class.forName(msodbc);
        con = DriverManager.getConnection(url, user, password);
        st = con.createStatement();
    }

    /**
     * 关闭链接
     *
     * @throws SQLException 数据库错误
     */
    private void closeConnect() throws SQLException {
        st.close();
        con.close();
    }

    /**
     * 插入数据库
     *
     * @param num  书编号
     * @param name 书名
     * @throws ClassNotFoundException 驱动未找到
     * @throws SQLException           数据库错误
     */
    public void insertRow(int num, String name) throws ClassNotFoundException, SQLException {
        connect(); //建立链接
        String sql = "insert into tb_book(num,name) values(" + num + ",'" + name + "');"; //sql
        st.executeUpdate(sql); //执行
        System.out.println("插入成功");
        closeConnect(); //关闭链接
    }


    public void selectRow() throws ClassNotFoundException, SQLException {
        connect();
        String sql = "select * from tb_book;";
        ResultSet rs = st.executeQuery(sql);
        while (rs.next()) {
            System.out.print("编号： " + rs.getString("num") + " ");
            System.out.println("书名： " + rs.getString("name"));
        }
        closeConnect();
    }
}
